﻿using System;
using System.Collections.Generic;
using System.Threading;
using Mbs;

namespace MessageBus.Threads.Module
{
    public interface IThreadView:IView
    {
        void AppendText(string content);
        void ClearContent();
    }

    public interface IThreadPresenter : IPresenter<IThreadView>
    {
        void Run();
    }

    public class ThreadPresenter : Presenter<IThreadView>, IThreadPresenter
    {
        string[] Topics;

        private readonly int TopicCount = 10;


        public override IEnumerator<IDisposable> Subscribe()
        {
            yield return CommandNames.RunThread.Subscribe<EventArgs>((s, e) => Run());
        }

        protected override void OnInit()
        {
            Disposes.Add(MessageBus.Subscribe<int>((s, e) => View.AppendText(e.ToString() + "\r\n")));
            Topics = new string[TopicCount];

            for (int i = 0; i < TopicCount; i++)
            {
                Topics[i] = "Topic" + (i + 1).ToString();
                Disposes.Add(Topics[i].Subscribe<int>((s, e) => View.AppendText(e.Name + ":" + e.ToString() + "\r\n")));
            }
        }
       
        public void Run()
        {
            View.ClearContent();

            List<Action> actions = new List<Action>(TopicCount + 1);
            actions.Add(Action);
            actions.AddRange(Array.ConvertAll<string, Action>(Topics, (topic) => () => Action(topic)));
            actions.ForEach(action => ThreadPool.QueueUserWorkItem((s) => action()));
        }

      
        private void Action()
        {
            for (int i = 1; i < TopicCount; i++)
            {
                MessageBus.Publish<int>(i);
            }
        }

        private const int SpinWait = 100;
        private void Action(string topic)
        {
            for (int i = 1; i < TopicCount; i++)
            {
                MessageBus.Publish<int>(topic, i);
                Thread.Sleep(SpinWait);
            }
        }

    }
}
